//
//  MYGChooseListView.swift
//  MYGrow
//
//  Created by 林矗 on 2024/3/17.
//

import UIKit

class MYGChooseListView: UIView {
    // MARK: - Property
    private var models: [MYGChooseViewModelProtocol] = []
    var currentSelectedItem: MYGChooseViewModelProtocol?
    var didSelectItemAction: ((Int, MYGChooseViewModelProtocol) ->())?
    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        configUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI
    private func configUI() {
        self.backgroundColor = .white
        addSubview(tableView)
    }
    
    // MARK: - Public funcs
    func reload(with models: [MYGChooseViewModelProtocol]) {
        self.models = models
        tableView.reloadData()
        let height = 60.0 * CGFloat(models.count)
        tableView.snp.remakeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.size.equalTo(CGSize(width: screenWidth, height: height))
            make.bottom.equalToSuperview().offset(-bottomSafeheight-10)
        }
    }
    
    // MARK: - lazy load
    private lazy var tableView: UITableView = {
        let tb = UITableView(frame: .zero, style: .plain)
        tb.separatorStyle = .none
        tb.backgroundColor = .white
        tb.delegate = self
        tb.dataSource = self
        tb.register(cellWithClass: MYGChooseListViewCell.self)
        return tb
    }()
}

extension MYGChooseListView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        models.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGChooseListViewCell.self)
        cell.title = models[indexPath.row].getTitle()
        cell.subtitle = models[indexPath.row].getSubtitle()
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        60
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        didSelectItemAction?(indexPath.row, models[indexPath.row])
    }
}
